import Cookies from 'js-cookie'
import { constantRoutes, asyncRoutes } from '@/router/routes'
const TokenKey = 'shangpinhui_back_token'

export function getToken() {
  return Cookies.get(TokenKey)
}

export function setToken(token) {
  return Cookies.set(TokenKey, token)
}

export function removeToken() {
  return Cookies.remove(TokenKey)
}

const routesKey = 'userRoutes'

export function setNewRoutes(routes) {
  localStorage.setItem(routesKey, JSON.stringify(routes))
}

export function getNewRoutes() {
  let str = localStorage.getItem(routesKey)
  if (str) {
    // 添加 component
    let routes = JSON.parse(str)
    let allRoutes = constantRoutes.concat(asyncRoutes)

    routes.forEach((item) => {
      for (let i = 0; i < allRoutes.length; i++) {
        if (item.path === allRoutes[i].path) {
          item.component = allRoutes[i].component
          try {
            if (item.children && item.children.length != 0) {
              item.children.forEach((value) => {
                for (let j = 0; j < allRoutes[i].children.length; j++) {
                  if (value.path === allRoutes[i].children[j].path) {
                    value.component = allRoutes[i].children[j].component
                    break
                  }
                }
              })
            }
          } catch (e) {
            console.log(item, allRoutes[i])
            debugger
          }
          break
        }
      }
    })
    
    return routes
  } else {
    return constantRoutes
  }
}
export function delNewRoutes() {
  localStorage.removeItem(routesKey)
}
